﻿using Cyss.Core.Cache;
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;

namespace Cyss.Core
{
    public class CacheStringLocalizer : ICacheStringLocalizer
    {
        private IStaticCacheManager _cacheManager;

        public CacheStringLocalizer(IStaticCacheManager cacheManager)
        {
            _cacheManager=cacheManager;
        }

        public string this[string key, bool isUseDefault = false, string DefaultValue = null]
        {
            get
            {
                var cacheKey = GetCahceKey(key);
                var value = GetCacheValue(cacheKey);
                if (!string.IsNullOrWhiteSpace(value))
                {
                    return value;
                }
                return key;
            }
        }

        public string this[string key, params object[] arguments]
        {
            get
            {
                var cacheKey = GetCahceKey(key);
                var value = GetCacheValue(cacheKey);
                if (string.IsNullOrWhiteSpace(value))
                {
                    return string.Format(value, arguments);
                }
                return key;
            }
        }

        public string Property<TItem>(Expression<Func<TItem, object>> ValueExpression, params object[] arguments)
        {
            var key = Localizer.GetResouresKey(ValueExpression);
            var cacheKey = GetCahceKey(key);
            var cacheValue = GetCacheValue(cacheKey);
            if (string.IsNullOrWhiteSpace(cacheValue))
            {
                cacheValue = ValueExpression.GetPropertieDisplay();
            }
            if (!string.IsNullOrWhiteSpace(cacheValue) && arguments!=null && arguments.Any())
            {
                cacheValue =string.Format(cacheValue, arguments);
            }
            return cacheValue;
        }

        public string Enum(Enum en)
        {
            var key = Localizer.GetResouresKey(en);
            var cacheKey = GetCahceKey(key);
            var cacheValue = GetCacheValue(cacheKey);
            if (string.IsNullOrWhiteSpace(cacheValue))
            {
                cacheValue = en.EnumDisplay();
            }
            return cacheValue;
        }

        /// <summary>
        /// 获取缓存key
        /// </summary>
        /// <param name="ResouresKey"></param>
        /// <returns></returns>
        private string GetCahceKey(string ResouresKey)
        {
            return $"LanguageResource:{CultureInfo.CurrentUICulture.Name}.{ResouresKey}";
        }

        /// <summary>
        /// 获取缓存值
        /// </summary>
        /// <param name="cahceKey"></param>
        /// <returns></returns>
        private string GetCacheValue(string cahceKey)
        {
            return _cacheManager.Get<string>(cahceKey.ToLower());
        }


    }
}
